package cn.gcxy.serlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DownloadServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		//寰楀埌涓婁紶鏂囦欢鐨勪繚瀛樼洰褰曪紝灏嗕笂浼犵殑鏂囦欢瀛樻斁浜嶹EB-INF鐩綍涓嬶紝涓嶅厑璁稿鐣岀洿鎺ヨ闂紝淇濊瘉涓婁紶鏂囦欢鐨勫畨鍏�
        String upload_base_url = req.getServletContext().getRealPath("/WEB-INF/upload");
        
        //鑾峰緱璇锋眰鏂囦欢鍚�  
        String filename = req.getParameter("file");  
        System.out.println(filename);  
         
        //璁剧疆鏂囦欢MIME绫诲瀷  
        resp.setContentType(getServletContext().getMimeType(filename));  
        //璁剧疆Content-Disposition  
        resp.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(filename, "UTF-8"));  

		File file = new File( upload_base_url +"/"+ filename);
		try {
			copy(new FileInputStream(file), resp.getOutputStream()); //杈撳嚭鏂囦欢鍐呭锛氫粠杈撳叆娴侊紙鏂囦欢锛�-銆嬭緭鍑烘祦锛坮esponse鐨勮緭鍑烘祦锛�
			resp.setHeader("Content-Type", "application/octet-stream");
			return;
		} catch (FileNotFoundException e) {
			req.setAttribute("exception", new FileNotFoundException("璇锋眰鐨勬枃浠朵笉瀛樺湪"));
			req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
		}
	}

	private static int copy(InputStream in, OutputStream out) throws IOException {
		int byteCount = 0;
		byte[] buffer = new byte[1024];
		int bytesRead = -1;
		while ((bytesRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, bytesRead);
			byteCount += bytesRead;
		}
		out.flush();
		return byteCount;
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
